package com.haitaoit.chengquan.module.center_service.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;

import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BackCall;
import com.haitaoit.chengquan.base.BaseActivity;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.DialogUtil;
import com.haitaoit.chengquan.utils.GetAbserlutePath;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.PreferenceUtils;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.utils.ZoomBitmap;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

public class QualificationAddActivity extends BaseActivity {
    @ViewInject(R.id.qualification_add_et)
    EditText qualification_add_et;
    @ViewInject(R.id.qualification_add_img)
    ImageView qualification_add_img;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView_V(R.layout.activity_qualification_add);
        setTitle_V("添加资质");
        setLeftShow(1, R.mipmap.left);
        backLeft_V();
        ViewUtils.inject(this);

    }

    @OnClick({R.id.qualification_add_img, R.id.qualification_add,})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.qualification_add_img:
                Dialog dlg = DialogUtil.ShowPhotoDialog(QualificationAddActivity.this, new BackCall() {
                    @Override
                    public void deal(int which, Object... obj) {
                        switch (which) {
                            case R.id.tv_photos:// 图库
                                Intent intent = new Intent();
                                intent.setAction(Intent.ACTION_GET_CONTENT);
                                intent.addCategory(Intent.CATEGORY_OPENABLE);
                                intent.setType("image/*");
                                intent.putExtra("aspectX", 1);
                                intent.putExtra("aspectY", 1);
                                intent.putExtra("outputX", 500);
                                intent.putExtra("outputY", 375);
                                intent.putExtra("crop", "true");
                                intent.putExtra("return-data", true);
                                startActivityForResult(intent, 2);
                                break;
                            case R.id.tv_camera:
                                Intent in = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                startActivityForResult(in, 2);
                                break;
                        }
                        super.deal(which, obj);
                    }
                });
                dlg.setCanceledOnTouchOutside(true);
                dlg.show();

                DisplayMetrics metric = new DisplayMetrics();
                this.getWindowManager().getDefaultDisplay().getMetrics(metric);
                int width = metric.widthPixels; // 屏幕宽度（像素）
                WindowManager.LayoutParams params = dlg.getWindow().getAttributes();
                params.width = width;
                params.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
                dlg.getWindow().setAttributes(params);
                break;
            case R.id.qualification_add:
                if (qualification_add_et.getText().toString().equals("")) {
                    ToastUtils.showToast("请输入资质标题！");
                } else if (file.equals("")) {
                    ToastUtils.showToast("请上传资质图片！");
                } else {
                    httpGetadd_user_qualification_introduced();
                }
                break;
        }
        super.onClick(v);
    }

    private void httpGetadd_user_qualification_introduced() {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        list.add(new NameValuePairSign("id", "0"));
        String sign = GetSign.genPackageSign(list);

        String url = Constant.add_user_qualification_introduced
                + "user_id=" + PreferenceUtils.getPrefString("user_id", "")
                + "&id=0&sign=" + sign;

        JSONObject json = new JSONObject();
        try {
            json.put("name", qualification_add_et.getText().toString());
            json.put("head_portrait", file);
        } catch (JSONException e1) {
            e1.printStackTrace();
        }

        HttpUtilsSingle.doPost(this, false, url, json, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            return;
                        case 0:// 成功
                            ToastUtils.showToast(Errmsg);
                            finish();
                            return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    // 记录文件名
    private String filename;
    // 上传的bitmap
    private Bitmap upbitmap;
    private String file = "";

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 1: // 解成bitmap,方便裁剪
                Bitmap bitmap = BitmapFactory.decodeFile(Environment
                        .getExternalStorageDirectory().getPath() + "/" + filename);
                float wight = bitmap.getWidth();
                float height = bitmap.getHeight();
                ZoomBitmap.zoomImage(bitmap, wight / 8, height / 8);
                upbitmap = ZoomBitmap.zoomImage(bitmap, wight / 19, height / 19);
                qualification_add_img.setImageBitmap(upbitmap);
                break;
            case 2:
                if (data != null) {
                    upbitmap = null;
                    if (data.getExtras() != null && !("").equals(data.getExtras())) {
                        upbitmap = (Bitmap) data.getExtras().get("data");
                    } else {
                        String str = data.getDataString();
                        if (str == null) {
                            return;
                        }
                        Uri uri = Uri.parse(str);
                        String path = GetAbserlutePath.getPath(this, uri);
                        if (path.endsWith("png") || path.endsWith("jpg")) {// 图片
                            upbitmap = ImageLoader.getInstance().loadImageSync("file://" + path);
                        } else {
                            ToastUtils.showToast("请选择.jpg或.png格式的图片！");
                            return;
                        }
                    }
                    upbitmap = getSmallBitmap(upbitmap);
                    file = bitmapToString(upbitmap);
                    qualification_add_img.setImageBitmap(upbitmap);
                }
                break;
        }
    }

    // 把bitmap转换成String
    public static String bitmapToString(Bitmap bgimage) {
        Bitmap bm = getSmallBitmap(bgimage);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 40, baos);
        byte[] b = baos.toByteArray();
        return Base64.encodeToString(b, Base64.DEFAULT);
    }

    // 根据路径获得图片并压缩，返回bitmap用于显示
    public static Bitmap getSmallBitmap(Bitmap bgimage) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, 480, 800);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;

        // return BitmapFactory.decodeFile(filePath, options);
        return ZoomBitmap.zoomImage(bgimage, bgimage.getWidth()
                / options.inSampleSize, bgimage.getHeight() / options.inSampleSize);
    }

    // 计算图片的缩放值
    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }
}
